

var spiralOrder = function (matrix) {
  if (!matrix.length || !matrix[0].length) {
    return []
  }

  const rows = matrix.length,
    columns = matrix[0].length
  const order = []
  let left = 0,
    right = columns - 1,
    top = 0,
    bottom = rows - 1
  while (left <= right && top <= bottom) {
    // 从左上到右上
    for (let column = left; column <= right; column++) {
      order.push(matrix[top][column])
    }
    // 从右上到右下
    for (let row = top + 1; row <= bottom; row++) {
      order.push(matrix[row][right])
    }
    // 从右下到左下，左下到左上
    if (left < right && top < bottom) {
      for (let column = right - 1; column > left; column--) {
        order.push(matrix[bottom][column])
      }
      for (let row = bottom; row > top; row--) {
        order.push(matrix[row][left])
      }
    }
    // 往里嵌1层
    ;[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1]
  }
  return order
}
